package chapter5_2_COW;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author huayuhao
 * @date 2020/12/16 16:41
 */
public class CopyList {

    private static volatile CopyOnWriteArrayList<String> arrayList = new CopyOnWriteArrayList<>();

    public static void main(String[] args) throws InterruptedException {

        arrayList.add("1");
        arrayList.add("2");
        arrayList.add("3");
        arrayList.add("4");
        arrayList.add("5");

        Thread threadA = new Thread(() -> {
            arrayList.set(1,"10");
            arrayList.remove(2);
            arrayList.remove(3);
        });
        //  因为在list发生修改之前生成迭代器 snapshot数组指向最原来的数组引用
        Iterator<String> iterator = arrayList.iterator();

        threadA.start();

        threadA.join();

        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

}
